<?php

namespace common\models;

use common\cache\DictCache;
use common\components\OrderBehavior;
use common\helpers\commonApi;
use common\helpers\PageApi;
use common\helpers\QueueApi;
use common\helpers\RedisApi;
use common\helpers\TransformApi;
use common\helpers\WeChatApi;
use Yii;
use yii\db\Exception;

/**
 * This is the model class for table "{{%order}}".
 *
 * @property int $id
 * @property string|null $order_sn 订单编号
 * @property int|null $userid 用户id
 * @property int|null $pay_status 支付状态
 * @property float|null $total_amount 总金额
 * @property float|null $pay_amount 支付金额
 * @property float|null $discount_amount 优惠金额
 * @property float|null $delivery_fee 配送费
 * @property int|null $total_num 订单商品数量
 * @property int|null $delivery_method 提货方式
 * @property int|null $delivery_campus_id 发货校区
 * @property string|null $delivery_lat 发货纬度
 * @property string|null $delivery_long 发货经度
 * @property string|null $delivery_info 发货地址信息
 * @property string|null $user_remarks 用户备注
 * @property int|null $snatch_sex 抢单限制性别
 * @property int|null $coupon_id 优惠券id
 * @property int|null $receipt_id 收获地址id
 * @property string|null $receipt_info 收获地址信息
 * @property string|null $receipt_long 收获经度
 * @property string|null $receipt_lat 收获纬度
 * @property string|null $create_time 下单时间
 * @property string|null $update_time 修改时间
 * @property int|null $order_status 订单状态
 * @property int|null $campus_id 校区id
 * @property string|null $party_order 第三方支付订单号
 * @property string|null $pay_time 支付时间
 * @property string|null $callback_info 回调信息
 * @property int|null $refund_status 退货状态
 * @property int|null $run_userid 跑腿id
 * @property int|null $run_status 跑腿状态
 * @property int|null $one_level 上上级
 * @property float|null $one_brokerage 上上级佣金
 * @property int|null $second_level 上级
 * @property float|null $second_brokerage 上级佣金
 * @property int|null $top_level 顶级
 * @property float|null $top_brokerage 顶级佣金
 * @property string|null $settl_time 结算时间
 * @property int|null $is_dis 是否已经分佣
 * @property float|null $trade_price 批发价
 * @property float|null $run_brokerage 跑腿佣金
 * @property float|null $ca_brokerage 校区金额
 * @property float|null $ca_price 校区价
 */
class Order extends BaseModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%order}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['userid', 'pay_status', 'total_num', 'delivery_method', 'delivery_campus_id', 'snatch_sex', 'coupon_id', 'receipt_id', 'order_status', 'campus_id', 'refund_status', 'run_userid', 'run_status', 'one_level', 'second_level', 'top_level', 'is_dis'], 'integer'],
            [['total_amount', 'pay_amount', 'discount_amount', 'delivery_fee', 'one_brokerage', 'second_brokerage', 'top_brokerage', 'trade_price', 'run_brokerage','ca_brokerage','ca_price'], 'number'],
            [['delivery_info', 'user_remarks', 'receipt_info', 'callback_info'], 'string'],
            [['create_time', 'update_time', 'pay_time', 'settl_time'], 'safe'],
            [['order_sn', 'delivery_lat', 'delivery_long', 'receipt_long', 'receipt_lat', 'party_order'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'order_sn' => '订单编号',
            'userid' => '用户id',
            'pay_status' => '支付状态',
            'total_amount' => '总金额',
            'pay_amount' => '支付金额',
            'discount_amount' => '优惠金额',
            'delivery_fee' => '配送费',
            'total_num' => '订单商品数量',
            'delivery_method' => '提货方式',
            'delivery_campus_id' => '发货校区',
            'delivery_lat' => '发货纬度',
            'delivery_long' => '发货经度',
            'delivery_info' => '发货地址信息',
            'user_remarks' => '用户备注',
            'snatch_sex' => '抢单限制性别',
            'coupon_id' => '优惠券id',
            'receipt_id' => '收获地址id',
            'receipt_info' => '收获地址信息',
            'receipt_long' => '收获经度',
            'receipt_lat' => '收获纬度',
            'create_time' => '下单时间',
            'update_time' => '修改时间',
            'order_status' => '订单状态',
            'campus_id' => '校区id',
            'party_order' => '第三方支付订单号',
            'pay_time' => '支付时间',
            'callback_info' => '回调信息',
            'refund_status' => '退货状态',
            'run_userid' => '跑腿id',
            'run_status' => '跑腿状态',
            'one_level' => '上上级',
            'one_brokerage' => '上上级佣金',
            'second_level' => '上级',
            'second_brokerage' => '上级佣金',
            'top_level' => '顶级',
            'top_brokerage' => '顶级佣金',
            'settl_time' => '结算时间',
            'is_dis' => '是否已经分佣',
            'trade_price' => '批发价',
            'run_brokerage' => '跑腿佣金',
            'ca_brokerage' => '校区金额',
            'ca_price' => '校区价',
        ];
    }

    public function getGoods()
    {
        return $this->hasMany(OrderGoods::className(), ['order_id' => 'id']);
    }

    /**
     * 创建订单号
     * @return mixed|string
     */
    public static function makeOrderid()
    {
        $orderId = time() . '' . rand(1000, 9999);
        if (self::find()->where(['order_sn' => $orderId])->exists()) {
            $orderId = self::makeOrderid();
        }
        return $orderId;
    }

    /**
     * 第三方创建订单号
     * @return mixed|string
     */
    public static function makePartyOrder($mark = 'wx')
    {
        $orderId = $mark . '_' . time() . '' . rand(1000, 9999);
        if (self::find()->where(['party_order' => $orderId])->exists()) {
            $orderId = self::makeOrderid();
        }
        return $orderId;
    }

    /**
     * 下单，金额为0将直接成功
     * @param $post 参数
     * @param $userid 用户id
     * @param $campus_id 校区id
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function placeOrder($post, $userid, $campus_id)
    {
        $data = $post['data'] ?? '';
        $delivery_method = $post['delivery_method'] ?? 1;//配送方式
        $user_remarks = $post['user_remarks'] ?? '';//用户备注
        $snatch_sex = $post['snatch_sex'] ?? 0;//限制性别
        $address_id = $post['address_id'] ?? '';//收获地址
        $uc_id = $post['uc_id'] ?? '';//卡券id
        if (!$data) {
            return commonApi::message('请选择商品', false);
        }
        $usercoupon = null;
        if ($uc_id) {
            $usercoupon = UserCoupon::find()->where(['id' => $uc_id, 'userid' => $userid, 'status' => 1, 'delete' => 0, 'use' => 0])->one();
            if (!$usercoupon) {
                return commonApi::message('卡券不错误', false);
            }
            if (!in_array($usercoupon->campus_id,[0,$campus_id])){
                return commonApi::message('该卡券不能在该校区使用',false);
            }
        }
        $receipt_id = '';
        $receipt_info = '';
        $receipt_long = '';
        $receipt_lat = '';
        if ($delivery_method == 2) {
            $address = Address::find()->where(['id' => $address_id, 'status' => 1])->asArray()->one();
            if (!$address) {
                return commonApi::message('请选择正确的收获地址', false);
            }
            if ($address['campus_id'] !== $campus_id) {
                return commonApi::message('地址选择错误', false);
            }
            $receipt_id = $address['id'];
            $receipt_info = json_encode($address);
            $receipt_long = $address['long'];
            $receipt_lat = $address['lat'];
        }

        $data = json_decode($data, true);
        if (!$data) {
            return commonApi::message('格式错误', false);
        }
        $campus = Campus::getCampusAll(['id' => $campus_id, 'status' => 1, 'delete' => 0]);
        $campus = array_column($campus, null, 'id');
        if (empty($campus[$campus_id])) {
            return commonApi::message('该校区已经暂停供货', false);
        }
        $cart_id = [];
        foreach ($data as &$datum) {
            $datum['campus_id'] = $campus_id;
            if (!empty($datum['cart_id'])) {
                $cart_id[] = $datum['cart_id'];
            }
        }
        $model = new GoodsSpec();
        $result = $model->calculation($data,0,$delivery_method);
        if (!$result['success']) {
            return $result;
        }
        $goods_total = $result['data']['goods_total'];
        $goods_spec = $result['data']['goods_spec'];
        $pay_time = '';
        $order_status = 0;
        $pay_status = 0;
        $order_sn = Order::makeOrderid();//订单号
        $system = System::getModel();
        $system->start_price = $system->start_price ?? 0;
        if ((int)$delivery_method==2){
            if ($system->start_price > 0 && $goods_total['total_amount'] < $system->start_price) {
                return commonApi::message('商品必须' . $system->start_price . '起送', false);
            }
        }
        //卡券使用
        if ($usercoupon) {
            $usercoupon->order_sn = $order_sn;
            $usercoupon->use = 1;
            $usercoupon->use_time = date('Y-m-d H:i:s');
            $goods_total['discount_amount'] = $usercoupon->discount_amount;
            $goods_total['pay_amount'] = $goods_total['pay_amount']-$usercoupon->discount_amount;
            if ($goods_total['pay_amount']<0){
                $goods_total['pay_amount'] = 0;
            }
        }
        if ($goods_total['pay_amount'] <= 0) {
            $party_order = '';
            $pay_time = date('Y-m-d H:i:s');
            $order_status = 1;
            if ((int)$delivery_method==1){
                $order_status = 2;
            }
            $pay_status = 1;
        } else {
            $config = [
                'app_id' => $system->a_appid,
                'mch_id' => $system->mch_id,
                'key' => $system->pay_key,
                'cert_path' => $system->cert_path,
                'key_path' => $system->cert_path,
            ];
            $party_order = Order::makePartyOrder();//第三方订单号
            $openid = User::find()->where(['id' => $userid])->select(['openid'])->scalar();
            $pay = new WeChatApi($config);
            $payResult = $pay->appletsPay($party_order, $goods_total['pay_amount'], '/api/notify/wx', $openid, '购买商品-' . $order_sn);
            if (!$payResult['success']) {
                return $payResult;
            }
        }
        //跑腿佣金 配送费-抽成
        $system->run_percentage = $system->run_percentage ?? 0;
        $percentage = 0;
        if ($system->run_percentage > 0) {
            $percentage = $goods_total['delivery_fee'] * $system->run_percentage / 100;
        }
        $run_brokerage = $goods_total['delivery_fee'] - $percentage;
        //校区佣金
        $saveData = [
            'total_amount' => $goods_total['total_amount'],
            'pay_amount' => $goods_total['pay_amount'],
            'discount_amount' => $goods_total['discount_amount'],
            'delivery_fee' => $goods_total['delivery_fee'],
            'total_num' => $goods_total['total_num'],
            'trade_price' => $goods_total['trade_price'],
            'ca_price' => $goods_total['ca_price'],
            'run_brokerage' => $run_brokerage,
            'order_sn' => $order_sn,
            'userid' => $userid,
            'delivery_method' => $delivery_method,
            'delivery_campus_id' => $campus_id,
            'delivery_lat' => $campus[$campus_id]['latitude'],
            'delivery_long' => $campus[$campus_id]['longitude'],
            'delivery_info' => json_encode($campus[$campus_id]),
            'user_remarks' => $user_remarks,
            'snatch_sex' => $snatch_sex,
            'receipt_id' => $receipt_id,
            'receipt_info' => $receipt_info,
            'receipt_long' => $receipt_long,
            'receipt_lat' => $receipt_lat,
            'campus_id' => $campus_id,
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s'),
            'order_status' => $order_status,
            'party_order' => $party_order,
            'pay_time' => $pay_time,
            'pay_status' => $pay_status,
            'coupon_id' => $uc_id,
        ];

        $model = new self();
        $model->load($saveData, '');
        TransformApi::tx(function () use ($model, $goods_spec, $payResult, $cart_id, $pay_status, $system, $usercoupon) {
            if ($model->save()) {
                if ($usercoupon){
                    $usercoupon->save();
                }
                $goods_spec = json_encode($goods_spec);
                $specArr = str_replace("order_id_value", $model->id, $goods_spec);
                $specArr = json_decode($specArr, true);
                $ordergoods = new OrderGoods();
                $field = array_keys($specArr[0]);
                $res = $ordergoods->insertAll($field, $specArr);
                if ($res) {
                    $msg = '创建订单成功';
                    if ($pay_status) {
                        $msg = '订单支付成功';
                        $payResult['data'] = ['is_pay'=>0];
                    }
                    if ($cart_id) {
                        Cart::deleteAll(['id' => $cart_id]);
                    }
                    if (!$pay_status) {
                        $cancel = $system->order_cancel ?? 0;
                        if ($cancel>0){
                            $cancel = $cancel * 60;
                            $callable = new OrderBehavior([
                                'method' => OrderBehavior::ORDER_CANCEL,
                                'params' => ['order_sn' => $model->order_sn, 'userid' => $model->userid],
                            ]);
                            (new QueueApi())->delay($cancel, $callable);
                        }
                    }
                    $dis = new OrderBehavior([
                        'method' => OrderBehavior::ORDER_DIS,
                        'params' => ['order_sn' => $model->order_sn, 'userid' => $model->userid],
                    ]);
                    (new QueueApi())->delay(0, $dis);
                    OrderLog::add(0, $model->order_sn, $model->userid, '', '用户提交订单', '用户提交订单');
                    return commonApi::message($msg, true, $payResult['data']);
                }
                throw new Exception('创建订单失败！！！');
            }
            throw new Exception(commonApi::getModelError($model));
        }, $resu);
        return $resu;
    }

    /**
     * 获取订单列表
     * @param $userid
     * @param $page
     * @return array
     */
    public function getList($userid, $where, $page)
    {
        $query = self::find()
            ->andFilterWhere(['userid' => $userid])
            ->andWhere($where)
            ->select(['order_sn', 'id', 'create_time', 'campus_id', 'total_amount', 'pay_amount', 'delivery_method', 'discount_amount', 'order_status', 'run_status', 'refund_status'])
            ->orderBy(['create_time' => SORT_DESC]);
        $data = PageApi::apiPage($query, $page);
        $ids = array_column($data['data'], 'id');
        $campus_ids = array_column($data['data'], 'campus_id');
        $campus = new Campus();
        $campusName = $campus->getCampusName($campus_ids);
        $orderGoods = new OrderGoods();
        $goods = $orderGoods->getList($ids);
        $order_status = DictCache::get('order_status');
        $delivery_method = DictCache::get('delivery_method');
        $run_status = DictCache::get('run_status');
        $refund_status = DictCache::get('refund_status');
        $statuIsretreat = Yii::$app->params['can_retreat'];
        foreach ($data['data'] as &$datum) {
            $datum['goods'] = $goods[$datum['id']] ?? [];
            $spec = array_column($datum['goods'], 'good_num');
            $total_num = array_sum($spec);
            $datum['campus_name'] = $campusName[$datum['campus_id']] ?? '';
            $datum['id'] = '';
            $datum['total_num'] = $total_num ?? 0;
            $datum['campus_id'] = '';
            $datum['create_time'] = date('Y-m-d H:i', strtotime($datum['create_time']));
            $datum['order_status_title'] = $order_status[$datum['order_status']] ?? '';
            $datum['d_method_title'] = $delivery_method[$datum['delivery_method']] ?? '';
            $datum['is_retreat'] = 0;
            $datum['refund_status_title'] = $refund_status[$datum['refund_status']] ?? '';
            if ($datum['refund_status']>0){
                $datum['order_status_title'] = '退货'.$refund_status[$datum['refund_status']] ?? '';
            }
            if (in_array($datum['order_status'], $statuIsretreat)) {
                if ($datum['refund_status'] == 0) {
                    $datum['is_retreat'] = 1;
                }
            }
            $datum['run_status_title'] = '';
            if ($datum['order_status'] > 0) {
                $datum['run_status_title'] = $run_status[$datum['run_status']] ?? '';
            }
        }
        return commonApi::message('ok', true, $data);
    }

    /**
     * 订单详情
     * @param $orderSn
     * @return array
     */
    public function getDetails($orderSn, $userid)
    {
        $order = self::find()->where(['order_sn' => $orderSn])->andWhere(['userid' => $userid])->one();
        if (!$order) {
            return commonApi::message('订单不存在!', false);
        }
        $orderGoods = new OrderGoods();
        $goods = $orderGoods->getList($order->id);
        $addrAn = $this->addrAn($order->delivery_info, $order->receipt_info, $order->delivery_method);
        $order_status = DictCache::get('order_status');
        $delivery_method = DictCache::get('delivery_method');
        $astrict_sex = DictCache::get('astrict_sex');
        $statuIsretreat = Yii::$app->params['can_retreat'];
        $is_retreat = 0;
        if (in_array($order->order_status, $statuIsretreat)) {
            if ($order->refund_status == 0) {
                $is_retreat = 1;
            }
        }
        $refund_status = DictCache::get('refund_status');
        if ($order->refund_status>0){
            $order_status_title = '退货'.$refund_status[$order->refund_status] ?? '';
            $order->order_status = 6;
        }else{
            $order_status_title = $order_status[$order->order_status] ?? '';
        }
        if ($order->snatch_sex==0){
            $order_snatch_sex = '不限';
        }else{
            $order_snatch_sex = $astrict_sex[$order->snatch_sex]??'';
        }
        $data = [
            'goods' => $goods[$order->id] ?? [],
            'total_amount' => $order->total_amount,
            'pay_amount' => $order->pay_amount,
            'discount_amount' => $order->discount_amount,
            'delivery_fee' => $order->run_brokerage,
            'user_remarks' => $order->user_remarks,
            'snatch_sex' => $order->snatch_sex,
            'snatch_sex_title' => $order_snatch_sex,
            'address' => $addrAn['address'],
            'order_status' => $order->order_status,
            'delivery_method' => $order->delivery_method,
            'order_status_title' => $order_status_title,
            'd_method_title' => $delivery_method[$order->delivery_method] ?? '',
            'is_retreat' => $is_retreat,
        ];
        return commonApi::message('ok', true, $data);
    }

    /**
     * 继续支付
     * @param $orderSn 订单号
     * @param $userid 用户id
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function continuePay($orderSn, $userid)
    {
        $order = self::find()->where(['order_sn' => $orderSn, 'userid' => $userid])->one();
        if (!$order) {
            return commonApi::message('订单不存在', false);
        }
        if ($order->pay_status !== 0) {
            return commonApi::message('订单不支持继续支付', false);
        }
        $key = 'continuePay_' . $orderSn;
        $redis = new RedisApi($key);
        $result = $redis->verificLock();
        if ($result) {
            return commonApi::message('请勿重复操作！', false);
        }
        $redis->lock($orderSn);
        $redis->expire(120);
        $config = System::pay();
        $openid = User::find()->where(['id' => $userid])->select(['openid'])->scalar();
        $party_order = Order::makePartyOrder();//第三方订单号
        $pay = new WeChatApi($config);
        $payResult = $pay->appletsPay($party_order, $order->pay_amount, '/api/notify/wx', $openid, '购买商品-' . $orderSn);
        if (!$payResult['success']) {
            $redis->unlock();
            return $payResult;
        }
        $order->create_time = date('Y-m-d H:i:s');
        $order->party_order = $party_order;
        if ($order->save()) {
            $redis->unlock();
            OrderLog::add(0, $order->order_sn, $order->userid, '', '用户再次提交订单', '用户再次提交订单');
            return commonApi::message('待支付订单', true, $payResult['data']);
        }
        $redis->unlock();
        return commonApi::message(commonApi::getModelError($order), false);
    }

    /**
     * 确认订单
     * @param array $orderSn 订单号
     * @param int $type 操作类型 0:用户 1:跑腿 2:校区 3:后台 4::系统
     * @param string $handle_id 操作人id
     * @return array
     */
    public function confirmDelivery($orderSn, $type = 0, $handle_id = '')
    {
        $order = self::find()->where(['order_sn' => $orderSn, 'order_status' => 4])->one();
        if (!$order) {
            return commonApi::message('订单不存在', false);
        }
        $key = 'confirmDelivery_' . $orderSn;
        $redis = new RedisApi($key);
        $result = $redis->verificLock();
        if ($result) {
            return commonApi::message('请勿重复操作！', false);
        }
        $redis->lock($orderSn);
        $redis->expire(120);
        $order->order_status = 5;
        $receiv = null;
        if ($order->run_status > 0 && !$order->run_userid) {
            $receiv = OrderReceiv::find()->where(['order_sn' => $orderSn, 'userid' => $order->run_userid])->one();
        }
        $runn = new Running();
        $user = new User();
        TransformApi::tx(function () use ($receiv, $order, $type, $handle_id, $runn, $user, $orderSn) {
            if ($order->one_level || $order->second_level) {
                $order->settl_time = date('Y-m-d H:i:s');
            }
            if ($order->save()) {
                if ($receiv) {
                    $receiv->is_receipt = 1;
                    $receiv->receipt_time = date('Y-m-d H:i:s');
                    $receiv->save();
                    $runn->getBrokerage($receiv->userid, $receiv->delivery_fee, $receiv->order_sn);
                }
                if ($order->one_level && $order->one_brokerage > 0) {
                    $user->operBrokerage($order->one_level, 2, 1, $order->one_brokerage, "获得【{$orderSn}】分销佣金");
                }
                if ($order->second_level && $order->second_brokerage > 0) {
                    $user->operBrokerage($order->second_level, 2, 1, $order->second_brokerage, "获得【{$orderSn}】分销佣金");
                }
                if ($order->top_level && $order->top_brokerage > 0) {
                    $user->operBrokerage($order->top_level, 2, 1, $order->top_brokerage, "获得【{$orderSn}】分销佣金");
                }
                OrderLog::add($type, $order->order_sn, $handle_id, '', '确认订单', '确认订单');
                return commonApi::message('确认成功');
            }
            throw new Exception('确认失败');
        }, $result);
        $redis->unlock();
        return $result;
    }

    /**
     * 地址解析
     * @param $delivery_info
     * @param $receipt_info
     * @param $delivery_method
     * @return array[]
     */
    public function addrAn($delivery_info, $receipt_info, $delivery_method)
    {
        //代取，显示用户收货地址
        //自提，展示店铺地址
        $delivery_info = $delivery_info ? json_decode($delivery_info, true) : [];
        $receipt_info = $receipt_info ? json_decode($receipt_info, true) : [];
        $address = [];
        if ($delivery_method == 1) {
            $address = [
                'name' => $delivery_info['name'],
                'address' => $delivery_info['address'],
                'longitude' => $delivery_info['longitude'],
                'latitude' => $delivery_info['latitude'],
                'contacts' => $delivery_info['contacts'],
                'phone' => $delivery_info['phone'],
            ];
        }
        if ($delivery_method == 2) {
            $address = [
                'name' => $receipt_info['campus_name'],
                'address' => $receipt_info['address'],
                'longitude' => $receipt_info['long'],
                'latitude' => $receipt_info['lat'],
                'contacts' => $receipt_info['consignee'],
                'phone' => $receipt_info['mobile'],
            ];
        }
        $delivery_arr = [
            'name' => $delivery_info['name'] ?? '',
            'address' => $delivery_info['address'] ?? '',
            'longitude' => $delivery_info['longitude'] ?? '',
            'latitude' => $delivery_info['latitude'] ?? '',
            'contacts' => $delivery_info['contacts'] ?? '',
            'phone' => $delivery_info['phone'] ?? '',
        ];
        $receipt_arr = [
            'name' => $receipt_info['campus_name'] ?? '',
            'address' => $receipt_info['address'] ?? '',
            'longitude' => $receipt_info['long'] ?? '',
            'latitude' => $receipt_info['lat'] ?? '',
            'contacts' => $receipt_info['consignee'] ?? '',
            'phone' => $receipt_info['mobile'] ?? '',
        ];
        return ['address' => $address, 'delivery_info' => $delivery_arr, 'receipt_info' => $receipt_arr];
    }

    /**
     * 分销订单
     * @param $myUserid 当前登录用户id
     * @param $userid 下级id
     * @param $status 状态 0:已结算 1:未结算 2:已失效
     * @param $page
     * @return array
     */
    public function disOrder($myUserid, $userid, $status, $page)
    {
        $statusAll = [
            0 => ['order_status' => 5, 'refund_status' => 0],
            1 => ['order_status' => [1, 2, 3, 4], 'refund_status' => 0],
            2 => ['!=', 'refund_status', 0],
        ];
        $where = [];
        if (!empty($statusAll[$status])) {
            $where = $statusAll[$status];
        }
        $andWhere = [];
        if ($userid) {
            $where['userid'] = $userid;
        } else {
            $andWhere = ['or', ['one_level' => $myUserid], ['second_level' => $myUserid], ['top_level' => $myUserid]];
        }
        $query = self::find()
            ->select(['id', 'order_sn', 'one_level', 'one_brokerage', 'second_level', 'second_brokerage', 'settl_time', 'create_time', 'order_status', 'refund_status', 'total_amount', 'top_level', 'top_brokerage'])
            ->where(['pay_status' => 1])
            ->andWhere($where)
            ->andWhere($andWhere)
            ->orderBy(['create_time' => SORT_DESC]);
        $data = PageApi::apiPage($query, $page);
        $ids = array_column($data['data'], 'id');
        $orderGoods = new OrderGoods();
        $goods = $orderGoods->getList($ids);
        $arr = [];
        $refund_status = DictCache::get('refund_status');
        foreach ($data['data'] as $datum) {
            $brokerage = 0;
            if ($myUserid == $datum['one_level']) {
                $brokerage = $datum['one_brokerage'];
            }
            if ($myUserid == $datum['second_level']) {
                $brokerage = $datum['second_brokerage'];
            }
            if ($myUserid == $datum['top_level']) {
                $brokerage = $datum['top_brokerage'];
            }
            if ($datum['refund_status'] !== 0) {
                $sett = '已失效';
                $tui = $refund_status[$datum['refund_status']] ?? '';
                $order_status_title = '退货' . $tui;
            } else {
                $sett = '待结算';
                $order_status_title = '待收货';
                if ($datum['order_status'] == 5) {
                    $sett = '已结算';
                    $order_status_title = '已收货';
                }
            }
            $arr[] = [
                'order_sn' => $datum['order_sn'],
                'brokerage' => $brokerage,
                'sett' => $sett,
                'settl_time' => $datum['settl_time'] ?? '',
                'create_time' => $datum['create_time'] ?? '',
                'goods' => $goods[$datum['id']] ?? [],
                'order_status_title' => $order_status_title,
                'total_amount' => $datum['total_amount'],
            ];
        }
        $data['data'] = $arr;
        return commonApi::message('ok', true, $data);
    }

    /**
     * 订单回调
     * @param $data 支付回调信息
     * @return bool
     */
    public function notify()
    {
        //获取支付回调参数
        $argList = func_get_args();
        $data = $argList[0] ?? [];
        TransformApi::tx(function () use ($data) {
            if (empty($data['out_trade_no'])) {
                return false;
            }
            $order = self::find()->where(['party_order' => $data['out_trade_no']])->one();
            if (!$order) {
                throw new Exception("暂无该订单【{$data['out_trade_no']}】");
            }
            if ($order->pay_status == 1) {
                throw new Exception("该订单已经支付成功【{$data['out_trade_no']}】");
            }
            if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS') {
                $order->pay_status = 1;
                $order->order_status = 1;
                $order->pay_time = date('Y-m-d H:i:s');
                $msg = '支付成功';
                if ((int)$order->delivery_method==1){//自提
                    $order->order_status = 2;
                }
            } else {
                $order->pay_status = 2;
                $msg = '支付失败';
            }
            $order->callback_info = json_encode($data);
            if ($order->save()) {
                $callable = new OrderBehavior([
                    'method' => OrderBehavior::ORDER_DIS,
                    'params' => ['order_sn' => $order->order_sn, 'order_id' => $order->id],
                ]);
                (new QueueApi())->delay(0, $callable);
                return commonApi::message($msg);
            }
            throw new Exception("该订单保存失败【{$data['out_trade_no']}】");
        }, $result);
        if ($result['success']) {
            return true;
        }
        return false;
    }
}